<?php
namespace app\console\controller;

use think\Build;
use think\Db;
use think\Url;
use think\Cache;
use think\Loader;
use think\Session;
use think\Request;
use think\Exception;
use think\Controller;
use app\client\model\ShopSpecAttr;
use app\console\model\Brand as BrandModel;
use app\client\model\ShopGoods as ShopGoodsModel;
use app\console\model\GoodsType as GoodsTypeModel;
use app\common\trilateral\Classify as ClassifyAlias;
use app\client\model\ShopGoodsSpec as ShopGoodsSpecModel;
use app\client\model\ShopGoodsAttr as ShopGoodsAttrModel;
use app\client\model\ShopGoodsType as ShopGoodsTypeModel;
use app\client\model\ShopGoodsFlag as ShopGoodsFlagModel;

class ShopGoods extends Controller
{

    /*
     * 店铺分类选择
     */
    public function classify()
    {
        // 读取分类店铺商品
        $data = GoodsTypeModel::where(['count' => '1'])->field('id,title,count')->order(['id' => 'asc'])->where('auding_status',2)->where('is_delete',1)->select();


        return $this->fetch('classify', [
            "mate_title" => '商品分类选择',
            'data'       => $data,
        ]);

    }



    /*
     * 店铺商品列表
     */
    public function index($pa = 10)
    {
        // 获取参数
        $inquire = Request::instance()->param();

        // halt($inquire['orderId']);

        // 搜索条件
        $condition = [];
        $sort = ['sort' => 'asc', 'id' => 'desc'];
        if (!empty($inquire['title'])) $condition['title'] = ['like', '%' . $inquire['title'] . '%'];
        //if (!empty($inquire['shop_class_id'])) $condition['parenTid'] = ['eq', $inquire['shop_class_id']];
        if (!empty($inquire['promotion'])) $condition['promotion'] = ['eq', $inquire['promotion']];
        //if (!empty($inquire['status'])) $condition['status'] = ['eq', $inquire['status']];
         if (!empty($inquire['state'])) $condition['state'] = ['eq', $inquire['state']];
        if (!empty($inquire['orderId'])) $sort = [$inquire['orderId'] => 'asc', 'id' => 'desc'];

        if (!empty($inquire['shop_class_id'])) $condition['goods_str'] = ['like','%,'.$inquire['shop_class_id'].',%'];

        // 读取店铺分类店铺商品
        $shopClassify = ShopGoodsTypeModel::where(['member_id' => Session::get('shop_id')])->field('id,title,parenTid,parentStr,count')->select();
        // 读取店铺商品
        $data = ShopGoodsModel::where($condition)->field('auding_status1,auding_status2,auding_status3,per,dc,code,auding_time,auding_id,auding_status,id,price,parenTid,sort,sale_number,title,update_time,create_id,create_time,recommend,related,promotion,status,state,inventory_hint,charges,inventory,shop_recommend,goods_id,auding_status')->order($sort)->paginate($pa, false, ['query' => $inquire]);
        if(isset($inquire['export'])){
            $this->push($data);
        }
        return $this->fetch('index', [
            'mate_title'   => '出售中的商品',
            'data'         => $data,
            'classify'     => ClassifyAlias::dimension(Cache::get('goodsType')),
            'shopClassify' => $shopClassify,

        ]);
    }

    /**
     * 商品对应每个业务员
     */
    public function salesman()
    {
        $where = [];
        $salesman_id = Request::instance()->param('salesman_id',0);
        $list = Salesman::salesman_public(input('id'),input('type'),$salesman_id);
        $data = Db::name('salesman s')
            ->join('manager m', 's.manage_id = m.id', 'left')
            ->field('m.username,m.nickname,m.create_time,s.*,m.id,m.telephone')
            ->where('m.level', 4)
            ->select()->toArray();
        $data = getMenuTree1($data,0);
        return view('', ['list' => $list,'sl' => $data]);
    }

    public function salesman_update()
    {
        try {
            $type_pk_id = input('id');
            $param = Request::instance()->param()['input'];
            $type = input('type');
            $cod = input('code');
            $code = [1 => '商品',3 => '礼包',2 => '服务'];
            //$param2 = Request::instance()->param()['input2'];
            if (!empty($param)) {
                $ret = false;
                foreach ($param as $k => $v) {
                    $find = Db::name('salesman_price')->where('salesman_id', $k)->where('type', $type)->where('type_pk_id', $type_pk_id)->find();
                    if ($find) { //存在就是修改
                        $ret = Db::name('salesman_price')->where('salesman_id', $k)->where('type', $type)->where('type_pk_id', $type_pk_id)->update(['per' => $v]);
                    } else {
                        $ret = Db::name('salesman_price')->insert([
                            'salesman_id' => $k,
                            'type' => $type,
                            'type_pk_id' => $type_pk_id,
                            'per' => $v, //$param[$k] = $v
                            //'person_price' => $param2[$k],
                            'create_time' => date('Y-m-d H:i:s', time())
                        ]);
                    }
                }
                if ($ret !== false) {
                    win($code[$type] . '分销比设置完毕', Url::build('salesman', ['id' => $type_pk_id, 'type' => $type,'code' => $cod]));
                }
            }
        } catch (Exception $e) {
            return json(['code' => $e->getCode(), 'message' => $e->getMessage(), 'line' => $e->getLine()]);
        }
    }

    public function push($data,$name = '库存商品导出')
    {

        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        error_reporting(E_ALL);
        date_default_timezone_set('Asia/Shanghai');

        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');
        $objPHPExcel = new \PHPExcel();

        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("管理员")
            ->setLastModifiedBy("管理员")
            ->setTitle("电话本导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("备份数据")
            ->setKeywords("excel")
            ->setCategory("result file");
        $objPHPExcel->setActiveSheetIndex(0)
            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
            ->setCellValue('A1', '科目代码')
            ->setCellValue('B1', '借贷方(绿色借方-灰色贷方)')
            ->setCellValue('C1', '商品ID')
            ->setCellValue('D1', '所属分类')
            ->setCellValue('E1', '商品名称')
            ->setCellValue('F1', '价钱')
            ->setCellValue('G1', '总库存')
            ->setCellValue('H1', '总销量')
            ->setCellValue('I1', '创建时间')
        ;
        $sheet1 = ['A', 'B', 'C', 'D', 'E'];

        for ($x = 0; $x < count($sheet1); $x++) {
            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(
                array(
                    'font'      => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' =>
                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
            );
        }

        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/

        $n = 0;
        foreach ($data as $v) {

            $num = $n + 2;
            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
                ->setCellValue('A' . $num, "\t".$v['code']."\t")
                ->setCellValue('B' . $num, $v['dc_text'])
                ->setCellValue('C' . $num, "\t".$v['id']."\t")
                ->setCellValue('D' . $num, $v['goods_type'])
                ->setCellValue('E' . $num, $v['title'])
                ->setCellValue('F' . $num, $v['price'])
                ->setCellValue('G' . $num, $v['inventory_sum'])
                ->setCellValue('H' . $num, $v['sale_number'])
                ->setCellValue('I' . $num, $v['create_time'])

            ;
            $n++;
        }

        $objPHPExcel->getActiveSheet(0)->setTitle('库存商品导出');
        $objPHPExcel->setActiveSheetIndex(0);

        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }

    /**
     * 栏目状态改变
     */
    public function dc($id, Request $request, ShopGoodsModel $model)
    {
        $id = $request->instance()->param('id');

        $status = $model->where('id', $id)->value('dc') == '1' ? 2 : 1;

        if ($model->where('id', $id)->update(['dc' => $status])) {
            return $status;
        }
        return false;
    }

    public function code(){
        $param = Request::instance()->param()['code'];

        if(!empty($param)){

            foreach ($param as $k => $v){

                $ret = Db::name('shop_goods')->where('id',$k)->setField('code',$v);
            }
            if($ret !== false){
                win('科目代码设置成功',Url::build('index'));
            }
        }

    }

    /**
     * @return array|mixed|\think\response\View
     * 出库list
     */
    public function chuku()
    {
        $inquire = Request::instance()->param();

        // halt($inquire['orderId']);
        $condition=[];
        // 搜索条件
        if (!empty($inquire['title'])) $condition['title'] = ['like', '%' . $inquire['title'] . '%'];
        if (!empty($inquire['shop_class_id'])) $condition['goods_str'] = ['like','%,'.$inquire['shop_class_id'].',%'];
        $param = Request::instance()->param();
        $cbj = 0 ;
        $zj = 0 ;
        $data = (new \app\console\model\ShopGoods())->order('id','desc')->where($condition)->paginate(10, false, ['query' => $param])->each(function ($item, $key) use(&$cbj,&$zj){
            $attr = Db::name('shop_spec_attr')->where('goods_id', $item->id)->where('shop_id',0)->select();
           $list = Db::name('shop_spec_attr')->where('goods_id', $item->id)->where('shop_id',0)->select()->toArray();
           foreach ($list as $k => &$v){
               $str = '';
               $cbj += $v['bit'];
               $zj += $v['inventory']*$v['bit'];
               $records = Db::name('shop_spec_attr_auding_status')
                   ->alias('s')
                   ->join('manager m','s.auding_id = m.id','left')
                   ->where(['spec_id' => $v['id'],'type' => 1])
                   ->column('auding_text');
               $records2 = Db::name('shop_spec_attr_auding_status')
                   ->alias('s')
                   ->join('manager m','s.auding_id = m.id','left')
                   ->where(['spec_id' => $v['id'],'type' => 2])
                   ->column('auding_text');
               $v['level'] = implode(',',$records);
               $v['level2'] = implode(',',$records2);
           }
            $item->list =$list;
            $item->count = count(Db::name('shop_spec_attr')->where('goods_id', $item->id)->where('shop_id',0)->select());
        });

        $data_cbj = (new \app\console\model\ShopGoods())->alias('sg')->where($condition)->join('shop_spec_attr ssa','ssa.goods_id = sg.id')->sum('bit');
        $data_zj = (new \app\console\model\ShopGoods())->alias('sg')->where($condition)->join('shop_spec_attr ssa','ssa.goods_id = sg.id')->field('sum(bit*ssa.inventory) zj')->find();
        if(isset($inquire['export'])){
            $this->push_chuku($data);
        }
        return view('', ['data' => $data,'cbj' => $data_cbj,'zj' => $data_zj['zj'],'classify'     => ClassifyAlias::dimension(Cache::get('goodsType'))]);
    }

    public function chuku_daochu()
    {
        $inquire = Request::instance()->param();

        // halt($inquire['orderId']);
        $condition=[];
        // 搜索条件
        if (!empty($inquire['title'])) $condition['title'] = ['like', '%' . $inquire['title'] . '%'];
        if (!empty($inquire['shop_class_id'])) $condition['goods_str'] = ['like','%,'.$inquire['shop_class_id'].',%'];
        $param = Request::instance()->param();
        $data = (new \app\console\model\ShopGoods())
            ->alias('sg')
            ->join('shop_spec_attr ssa','ssa.goods_id = sg.id')
            ->where('ssa.shop_id',0)
            ->order('sg.id','desc')
            ->where($condition)
            ->select();
        if(isset($inquire['export'])){
            $this->push_chuku($data);
        }

        return view('', ['data' => $data,'classify'     => ClassifyAlias::dimension(Cache::get('goodsType'))]);
    }

    public function push_chuku($data,$name = '总库库存导出')
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        error_reporting(E_ALL);
        date_default_timezone_set('Asia/Shanghai');

        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');
        $objPHPExcel = new \PHPExcel();

        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("管理员")
            ->setLastModifiedBy("管理员")
            ->setTitle("电话本导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("备份数据")
            ->setKeywords("excel")
            ->setCategory("result file");
        $objPHPExcel->setActiveSheetIndex(0)
            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
            ->setCellValue('A1', 'ID')
            ->setCellValue('B1', '商品名称')
            ->setCellValue('C1', '属性值')
            ->setCellValue('D1', '属性库存')
            ->setCellValue('E1', '成本价')
            ->setCellValue('F1', '总价')
        ;
        $sheet1 = ['A', 'B', 'C', 'D', 'E','F'];

        for ($x = 0; $x < count($sheet1); $x++) {
            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(
                array(
                    'font'      => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' =>
                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
            );
        }

        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/

        $n = 0;
        foreach ($data as $v) {

            $num = $n + 2;
            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
                ->setCellValue('A' . $num, $v['id'])
                ->setCellValue('B' . $num, $v['title'])
                ->setCellValue('C' . $num,$v['attribute'])
                ->setCellValue('D' . $num, $v['inventory'])
                ->setCellValue('E' . $num, $v['bit'])
                ->setCellValue('F' . $num, $v['inventory']*$v['bit'])
            ;
            $n++;
        }

        $objPHPExcel->getActiveSheet(0)->setTitle('总库库存导出');
        $objPHPExcel->setActiveSheetIndex(0);

        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }



    /**
     * @param $id
     * @return array|mixed|\think\response\View
     * 总库存出库到门店
     */
    public function chuku_shop($id)
    {
        $param = Request::instance()->param();
        if (Request::instance()->isPost()) {

            if ($param['shop_id'] <= 0) {
                fail('必须选择门店');
            }
            if ($param['count'] <= 0) {
                fail('出库数量必须大于0');
            }
            $count = count($param['shop_id']) * $param['count'];
            if ($count > $param['inventory']) {
                fail('出库数量不能大于总库存');
            }
            if (isset($param['auding_status'])) { //有审核状态 审核权限人 2是审核成功
                //多次审核
                $role_id = session('role_id');

                if($role_id == 1 || $role_id == 2){
                    $role_id = 11;  //如果是超级管理员或者管理员就当一级审核原来玩

                }
                if($role_id == 11){
                    $auding_text = '一级审核';
                }
                if($role_id == 12){
                    $auding_text = '二级审核';
                }
                if($role_id == 13){
                    $auding_text = '三级审核';
                }
                $manage_id = session('manage_id');
                //超级管理员1 管理员2 一级审核员11 二级审核员12 三级审核员13
                $status = false;

                if($param['auding_status'] != 2){ //不是成功就是删除 重新来
                    Db::name('shop_spec_attr_auding_status')->where('spec_id',$param['id'])->delete(); //全部删除重新审核
                    Db::name('shop_spec_attr')->where('id',$param['id'])->setField('reason',$param['reason']);
                    fail('您不同意审核,审核重新开始');
                }else{
                    //成功
                    $find = Db::name('shop_spec_attr_auding_status')->where([
                        'type' => 2,
                        'spec_id' => $param['id'],
                        'auding_status' => $param['auding_status'],
                        'role_id' => $role_id
                    ])->find(); //当前会员

                    if(!empty($find)) fail('本级别已经审核过');
                    $select = Db::name('shop_spec_attr_auding_status')->where([
                        'type' => 2,
                        'spec_id' => $param['id'],
                    ])->select(); //统计数量
                    if(count($select) == 2){ //如果已经有2条同意了 那就是正常添加了
                        Db::name('shop_spec_attr_auding_status')->where([
                            'type' => 2,
                            'spec_id' => $param['id'],
                        ])->delete(); //删除统计记录
                        foreach ($param['shop_id'] as $k => $v) {
                            $goods_attr = Db::name('shop_spec_attr')->where('goods_id', $param['goods_id'])->where('shop_id', $v)->where('attribute', $param['attribute'])->find();
                            if ($goods_attr) {
                                Db::name('shop_spec_attr')->where('goods_id', $param['goods_id'])->where('shop_id', $v)->where('attribute', $param['attribute'])->setInc('inventory', $param['count']);

                            } else {
                                Db::name('shop_spec_attr')->insert([
                                    'goods_id' => $param['goods_id'],
                                    'shop_id' => $v,
                                    'attribute' => $param['attribute'],
                                    'inventory' => $param['count']
                                ]);

                            }
                            $this->insert_records(2, $param['count'], $id, $v);
                            Db::name('shop_spec_attr')->where('goods_id', $param['goods_id'])->where('shop_id', 0)->where('attribute', $param['attribute'])->setDec('inventory', $param['count']);


                        }
                        win('出库成功', Url::build('chuku'));
                    }
                    Db::name('shop_spec_attr_auding_status')->insert([
                        'auding_text' => $auding_text,
                        'shop_str' => implode(',',$param['shop_id']),
                        'count' => $param['count'],
                        'bit' => 0,
                        'type' => 2,
                        'spec_id' => $param['id'],
                        'auding_status' => $param['auding_status'],
                        'auding_id' => $manage_id,
                        'role_id' => $role_id,
                        'create_time' => date('Y-m-d H:i:s',time())

                    ]);


                    Db::name('shop_spec_attr')->where('id',$param['id'])->setField('reason',''); //成功 就没有失败原因 清空
                    win('审核完毕',Url::build('chuku'));
                }

            }

        }

        $shop_list = Db::name('shop')->where('is_delete', 1)->where('auding_status', 2)->select();
        $shenhe = Db::name('shop_spec_attr_auding_status')
            ->alias('s')
            ->join('manager m','s.auding_id = m.id')
            ->where(['spec_id' => $param['id'],'type' => 2])
            ->find();
        $records = Db::name('shop_spec_attr_auding_status')
            ->alias('s')
            ->join('manager m','s.auding_id = m.id','left')
            ->where(['spec_id' => $param['id'],'type' => 2])
            ->select()->toArray();
        foreach ($records as $k => &$v){
            if($v['role_id'] == 11){
                $v['level'] = '一级审核';
            }
            if($v['role_id'] == 12){
                $v['level'] = '二级审核';
            }
            if($v['role_id'] == 13){
                $v['level'] = '三级审核';
            }
        }
        return view('', ['shop_list' => $shop_list,'item' => $shenhe,'records' => $records]);
    }




    public function ruku($id){
        $param = Request::instance()->param();

        if(Request::instance()->isPost()){
            if (isset($param['auding_status'])) { //有审核状态 审核权限人 2是审核成功
                //多次审核
                $role_id = session('role_id');

                if($role_id == 1 || $role_id == 2){
                    $role_id = 11;  //如果是超级管理员或者管理员就当一级审核原来玩

                }
                if($role_id == 11){
                    $auding_text = '一级审核';
                }
                if($role_id == 12){
                    $auding_text = '二级审核';
                }
                if($role_id == 13){
                    $auding_text = '三级审核';
                }
                $manage_id = session('manage_id');
                //超级管理员1 管理员2 一级审核员11 二级审核员12 三级审核员13
                $status = false;

                if($param['auding_status'] != 2){ //不是成功就是删除 重新来
                    Db::name('shop_spec_attr_auding_status')->where('spec_id',$param['id'])->delete(); //全部删除重新审核
                    Db::name('shop_spec_attr')->where('id',$param['id'])->setField('reason',$param['reason']);
                    fail('您不同意审核,审核重新开始');
                }else{
                    //成功
                    $find = Db::name('shop_spec_attr_auding_status')->where([
                        'type' => 1,
                        'spec_id' => $param['id'],
                        'auding_status' => $param['auding_status'],
                        'role_id' => $role_id
                    ])->find(); //当前会员

                    if(!empty($find)) fail('本级别已经审核过');
                    $select = Db::name('shop_spec_attr_auding_status')->where([
                        'type' => 1,
                        'spec_id' => $param['id'],
                    ])->select(); //统计数量
                    if(count($select) == 2){ //如果已经有2条同意了 那就是正常添加了
                        Db::name('shop_spec_attr_auding_status')->where([
                            'type' => 1,
                            'spec_id' => $param['id'],
                        ])->delete(); //删除统计记录
                        Db::name('shop_spec_attr_bit')->insert([
                            'spec_attr_id' => $param['id'],
                            'goods_id' => $param['goods_id'],
                            'bit' => $param['bit'],
                            'count' => $param['count'],
                            'total_bit' => $param['bit']*$param['count'],
                            'attribute' => $param['attribute'],
                            'inventory' => $param['inventory'],
                            'after_inventory' => $param['inventory']+$param['count'],
                            'create_time' => date('Y-m-d H:i:s',time())
                        ]);
                        $goods_attr = Db::name('shop_spec_attr')->where('id',$id)->setInc('inventory',$param['count']);
                        Db::name('shop_spec_attr')->where('id',$id)->update(['count' =>$param['count'],'bit' => $param['bit'],'total_bit' => $param['count']*$param['bit']]);
                        if($goods_attr){
                            $this->insert_records(1,$param['count'],$id);
                            win('入库成功',Url::build('chuku'));
                        }
                    }
                    Db::name('shop_spec_attr_auding_status')->insert([
                        'auding_text' => $auding_text,
                        'count' => $param['count'],
                        'bit' => $param['bit'],
                        'type' => 1,
                        'spec_id' => $param['id'],
                        'auding_status' => $param['auding_status'],
                        'auding_id' => $manage_id,
                        'role_id' => $role_id,
                        'create_time' => date('Y-m-d H:i:s',time())

                        ]);


                    Db::name('shop_spec_attr')->where('id',$param['id'])->setField('reason',''); //成功 就没有失败原因 清空
                    win('审核完毕',Url::build('chuku'));
                }
//                if($role_id == 1 || $role_id == 2 || $role_id == 11){
//                    Db::name('shop_spec_attr_auding_status')->insert();
//                    if($auding_status1 == 2 && $auding_status2 == 2 && $auding_status3 ==2){ //这有这一种情况是审核通过 其他全部是失败
//                        $status = true;
//                    }
//
//                }
//                if($role_id == 12){ //2级审核
//                    if($auding_status1 == 2 && $auding_status1 == 2 && $auding_status3 ==2){ //这有这一种情况是审核通过 其他全部是失败
//                        $status = true;
//                    }
//                }
//                if($role_id == 13){
//                    if($auding_status1 == 2 && $auding_status1 == 2 && $auding_status2 ==2){ //这有这一种情况是审核通过 其他全部是失败
//
//                        $status = true;
//                    }
//                }
//                if($status == true){
//                    $data->auding_status = 2;
//                    Db::name('member_coupon')->where('coupon_id',$data->id)->setField('auding_status',2);
//                    foreach (explode(',',Db::name('coupon')->where('id',$data->id)->value('shop_assignor_id')) as $k => $v){
//                        (new \app\index\controller\MemberMessage())->jpushMessage($v,'恭喜您获得优惠券'.Db::name('coupon')->where('id',$data->id)->value('number').'张',Db::name('coupon')->where('id',$data->id)->value('title'),3);
//
//                    }
//
//                }else{
//                    // $data->auding_status = $data->auding_status;使用默认提交值
//                    $data->auding_status = 3; //必须失败 否则 默认提交过来的auding_status 自动还是变成 1 2 3 状态;
//                    Db::name('member_coupon')->where('coupon_id',$data->id)->setField('auding_status',1);
//                }

            }
//            Db::name('shop_spec_attr_bit')->insert([
//                'spec_attr_id' => $param['id'],
//                'goods_id' => $param['goods_id'],
//                'bit' => $param['bit'],
//                'count' => $param['count'],
//                'total_bit' => $param['bit']*$param['count'],
//                'attribute' => $param['attribute'],
//                'inventory' => $param['inventory'],
//                'after_inventory' => $param['inventory']+$param['count'],
//                'create_time' => date('Y-m-d H:i:s',time())
//            ]);
//            $goods_attr = Db::name('shop_spec_attr')->where('id',$id)->setInc('inventory',$param['count']);
//            Db::name('shop_spec_attr')->where('id',$id)->update(['count' =>$param['count'],'bit' => $param['bit'],'total_bit' => $param['count']*$param['bit']]);
//            if($goods_attr){
//                $this->insert_records(1,$param['count'],$id);
//
//                win('入库成功',Url::build('chuku'));
//            }

        }
        $shenhe = Db::name('shop_spec_attr_auding_status')
            ->alias('s')
            ->join('manager m','s.auding_id = m.id')
            ->where(['spec_id' => $param['id'],'type' => 1])
            ->find();
        $records = Db::name('shop_spec_attr_auding_status')
            ->alias('s')
            ->join('manager m','s.auding_id = m.id','left')
            ->where(['spec_id' => $param['id'],'type' => 1])
            ->select()->toArray();
        foreach ($records as $k => &$v){
            if($v['role_id'] == 11){
                $v['level'] = '一级审核';
            }
            if($v['role_id'] == 12){
                $v['level'] = '二级审核';
            }
            if($v['role_id'] == 13){
                $v['level'] = '三级审核';
            }


        }
        return view('',['item' => $shenhe,'records' => $records]);
    }

    /**
     * @return array|mixed|\think\response\View
     * 门店出库到门店列表
     */
    public function shop_to_shop()
    {
        $param = Request::instance()->param();
        $where = [];
        $whereTitle = [];

        if(!empty($param['shop_id'])) $where['shop_id'] = ['eq',Request::instance()->param('shop_id')];
        if(!empty($param['title'])) $whereTitle['sg.title'] = ['like','%'.$param['title'].'%'];
        if(\session('auding_status') == 2){

        }else{
            $where['shop_id'] = ['eq',\session('shop_id')];
        }
        $data = (new \app\console\model\ShopGoods())
            ->alias('sg')
            ->join('shop_spec_attr ssa','sg.id = ssa.goods_id')
            ->where($where)
            ->where($whereTitle)
            ->where('ssa.shop_id','gt',0)
            ->field('sg.*,ssa.shop_id')
            ->order('sg.id desc')
            ->group('ssa.goods_id')
            ->paginate(10, false, ['query' => $param])->each(function ($item, $key)  use ($where){
                $list = Db::name('shop_spec_attr ssa')
                    ->join('shop s','ssa.shop_id = s.id')
                    ->where('ssa.goods_id', $item->id)
                    ->where($where)
                    ->field('ssa.*,s.shop_title')
                    ->where('ssa.shop_id','gt',0)
                    ->select()->toArray();
                foreach ($list as $k => &$v){
                    $str = '';
                    $records = Db::name('shop_spec_attr_auding_status')
                        ->alias('s')
                        ->join('manager m','s.auding_id = m.id','left')
                        ->where(['spec_id' => $v['id'],'type' => 3])
                        ->column('auding_text');
                    $records2 = Db::name('shop_spec_attr_auding_status')
                        ->alias('s')
                        ->join('manager m','s.auding_id = m.id','left')
                        ->where(['spec_id' => $v['id'],'type' => 4])
                        ->column('auding_text');
                    $v['level'] = implode(',',$records);
                    $v['level2'] = implode(',',$records2);

                }
                $item->list =$list;
            $item->count = count(Db::name('shop_spec_attr')->where($where)->where('goods_id', $item->id)->where('shop_id','gt',0)->select());
        });

        $shop_list = Db::name('shop')->where('auding_status',2)->where('is_delete',1)->select();
        return view('', ['data' => $data,'shop_list' => $shop_list]);
    }

    public function shop_to_shop_daochu()
    {
        $param = Request::instance()->param();
        $where = [];
        if(!empty($param['shop_id'])){
            $where['ssa.shop_id'] = ['eq',Request::instance()->param('shop_id')];
        }
        if(!empty($param['title'])) $where['sg.title'] = ['like','%'.$param['title'].'%'];
        if(\session('auding_status') == 2){
        }else{
            $where['shop_id'] = ['eq',\session('shop_id')];
        }
        $data = Db::name('shop_spec_attr ssa')
            ->where($where)
            ->join('shop_goods sg','ssa.goods_id = sg.id')
            ->join('shop s','ssa.shop_id = s.id')
            ->field('ssa.*,s.shop_title,sg.title')
            ->where('ssa.shop_id','gt',0)
            ->select();
       $this->push_hop_chuku($data);
    }
    public function push_hop_chuku($data,$name = '分店出库导出')
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        error_reporting(E_ALL);
        date_default_timezone_set('Asia/Shanghai');

        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');
        $objPHPExcel = new \PHPExcel();

        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("管理员")
            ->setLastModifiedBy("管理员")
            ->setTitle("电话本导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("备份数据")
            ->setKeywords("excel")
            ->setCategory("result file");
        $objPHPExcel->setActiveSheetIndex(0)
            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
            ->setCellValue('A1', 'ID')
            ->setCellValue('B1', '商品名称')
            ->setCellValue('C1', '属性值')
            ->setCellValue('D1', '属性库存')
            ->setCellValue('E1', '门店名称')
        ;
        $sheet1 = ['A', 'B', 'C', 'D', 'E','F'];

        for ($x = 0; $x < count($sheet1); $x++) {
            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(
                array(
                    'font'      => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' =>
                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
            );
        }

        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/

        $n = 0;
        foreach ($data as $v) {

            $num = $n + 2;
            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
                ->setCellValue('A' . $num, $v['id'])
                ->setCellValue('B' . $num, $v['title'])
                ->setCellValue('C' . $num,$v['attribute'])
                ->setCellValue('D' . $num, $v['inventory'])
                ->setCellValue('E' . $num, $v['shop_title'])
            ;
            $n++;
        }

        $objPHPExcel->getActiveSheet(0)->setTitle('分店出库导出');
        $objPHPExcel->setActiveSheetIndex(0);

        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }

    /**
     * @param $id
     * @return array|mixed|\think\response\View
     * 门店出库到门店
     */
    public function chuku_shop_shop($id){
        $param = Request::instance()->param();
        if(Request::instance()->isPost()){

            if($param['shop_id'] <=0){
                //fail('必须选择门店');
            }
            if($param['count'] <=0){
                fail('出库数量必须大于0');
            }

            $count = count($param['shop_id'])*$param['count'];
            if($count > $param['inventory']){
                fail('出库数量不能大于总库存');
            }

            if (isset($param['auding_status'])) { //有审核状态 审核权限人 2是审核成功
                //多次审核
                $role_id = session('role_id');

                if($role_id == 1 || $role_id == 2){
                    $role_id = 11;  //如果是超级管理员或者管理员就当一级审核原来玩

                }
                if($role_id == 11){
                    $auding_text = '一级审核';
                }
                if($role_id == 12){
                    $auding_text = '二级审核';
                }
                if($role_id == 13){
                    $auding_text = '三级审核';
                }
                $manage_id = session('manage_id');
                //超级管理员1 管理员2 一级审核员11 二级审核员12 三级审核员13
                $status = false;

                if($param['auding_status'] != 2){ //不是成功就是删除 重新来
                    Db::name('shop_spec_attr_auding_status')->where('spec_id',$param['id'])->delete(); //全部删除重新审核
                    Db::name('shop_spec_attr')->where('id',$param['id'])->setField('reason',$param['reason']);
                    fail('您不同意审核,审核重新开始');
                }else{
                    //成功
                    $find = Db::name('shop_spec_attr_auding_status')->where([
                        'type' => 4,
                        'spec_id' => $param['id'],
                        'auding_status' => $param['auding_status'],
                        'role_id' => $role_id
                    ])->find(); //当前会员

                    if(!empty($find)) fail('本级别已经审核过');
                    $select = Db::name('shop_spec_attr_auding_status')->where([
                        'type' => 4,
                        'spec_id' => $param['id'],
                    ])->select(); //统计数量
                    if(count($select) == 2){ //如果已经有2条同意了 那就是正常添加了
                        Db::name('shop_spec_attr_auding_status')->where([
                            'type' => 4,
                            'spec_id' => $param['id'],
                        ])->delete(); //删除统计记录
                        foreach ($param['shop_id'] as $k => $v){
                            $goods_attr = Db::name('shop_spec_attr')->where('goods_id',$param['goods_id'])->where('shop_id',$v)->where('attribute',$param['attribute'])->find();
                            if($goods_attr){
                                Db::name('shop_spec_attr')->where('goods_id',$param['goods_id'])->where('shop_id',$v)->where('attribute',$param['attribute'])->setInc('inventory',$param['count']);

                            }else{
                                Db::name('shop_spec_attr')->insert([
                                    'goods_id' => $param['goods_id'],
                                    'shop_id' => $v,
                                    'attribute' => $param['attribute'],
                                    'inventory' => $param['count']
                                ]);

                            }
                            if($count == $param['inventory']){ //当前门店所有库存全部清空 那就删除本条数据了
                                Db::name('shop_spec_attr')->where('id',$id)->delete();
                            }else{
                                Db::name('shop_spec_attr')->where('id',$id)->setDec('inventory',$param['count']);
                            }

                            $this->insert_records(4,$param['count'],$id,$v);
                        }
                        win('出库成功',Url::build('shop_to_shop'));
                    }
                    Db::name('shop_spec_attr_auding_status')->insert([
                        'auding_text' => $auding_text,
                        'shop_str' => implode(',',$param['shop_id']),
                        'count' => $param['count'],
                        'bit' => 0,
                        'type' => 4,
                        'spec_id' => $param['id'],
                        'auding_status' => $param['auding_status'],
                        'auding_id' => $manage_id,
                        'role_id' => $role_id,
                        'create_time' => date('Y-m-d H:i:s',time())

                    ]);


                    Db::name('shop_spec_attr')->where('id',$param['id'])->setField('reason',''); //成功 就没有失败原因 清空
                    win('审核完毕',Url::build('shop_to_shop'));
                }

            }


        }

        $shop_list = Db::name('shop')->where('is_delete',1)->where('auding_status',2)->select();
        $shenhe = Db::name('shop_spec_attr_auding_status')
            ->alias('s')
            ->join('manager m','s.auding_id = m.id')
            ->where(['spec_id' => $param['id'],'type' => 4])
            ->find();
        $records = Db::name('shop_spec_attr_auding_status')
            ->alias('s')
            ->join('manager m','s.auding_id = m.id','left')
            ->where(['spec_id' => $param['id'],'type' => 4])
            ->select()->toArray();
        foreach ($records as $k => &$v){
            if($v['role_id'] == 11){
                $v['level'] = '一级审核';
            }
            if($v['role_id'] == 12){
                $v['level'] = '二级审核';
            }
            if($v['role_id'] == 13){
                $v['level'] = '三级审核';
            }
        }
        return view('',['shop_list' => $shop_list,'item' => $shenhe,'records' => $records]);
    }

    /**
     * @param $id
     * @return array|mixed|\think\response\View
     * 门店出库总库
     */
    public function chuku_shop_adminer($id){
        $param = Request::instance()->param();
        if(Request::instance()->isPost()){

            if($param['count'] <=0){
                fail('出库数量必须大于0');
            }

            $count = $param['count'];
            if($count > $param['inventory']){
                fail('出库数量不能大于总库存');
            }

            if (isset($param['auding_status'])) { //有审核状态 审核权限人 2是审核成功
                //多次审核
                $role_id = session('role_id');

                if($role_id == 1 || $role_id == 2){
                    $role_id = 11;  //如果是超级管理员或者管理员就当一级审核原来玩

                }
                if($role_id == 11){
                    $auding_text = '一级审核';
                }
                if($role_id == 12){
                    $auding_text = '二级审核';
                }
                if($role_id == 13){
                    $auding_text = '三级审核';
                }
                $manage_id = session('manage_id');
                //超级管理员1 管理员2 一级审核员11 二级审核员12 三级审核员13
                $status = false;

                if($param['auding_status'] != 2){ //不是成功就是删除 重新来
                    Db::name('shop_spec_attr_auding_status')->where('spec_id',$param['id'])->delete(); //全部删除重新审核
                    Db::name('shop_spec_attr')->where('id',$param['id'])->setField('reason',$param['reason']);
                    fail('您不同意审核,审核重新开始');
                }else{
                    //成功
                    $find = Db::name('shop_spec_attr_auding_status')->where([
                        'type' => 3,
                        'spec_id' => $param['id'],
                        'auding_status' => $param['auding_status'],
                        'role_id' => $role_id
                    ])->find(); //当前会员

                    if(!empty($find)) fail('本级别已经审核过');
                    $select = Db::name('shop_spec_attr_auding_status')->where([
                        'type' => 3,
                        'spec_id' => $param['id'],
                    ])->select(); //统计数量
                    if(count($select) == 2){ //如果已经有2条同意了 那就是正常添加了
                        Db::name('shop_spec_attr_auding_status')->where([
                            'type' => 3,
                            'spec_id' => $param['id'],
                        ])->delete(); //删除统计记录
                        //
                        $goods_attr = Db::name('shop_spec_attr')->where('goods_id',$param['goods_id'])->where('shop_id',0)->where('attribute',$param['attribute'])->find();
                        if($goods_attr){ //正常来说 总库肯定是存在的
                            Db::name('shop_spec_attr')->where('goods_id',$param['goods_id'])->where('shop_id',0)->where('attribute',$param['attribute'])->setInc('inventory',$param['count']);

                        }else{
                            fail('总库当前属性不存在');
                        }
                        if($count == $param['inventory']){ //当前门店所有库存全部清空 那就删除本条数据了
                            Db::name('shop_spec_attr')->where('id',$id)->delete();
                        }else{
                            Db::name('shop_spec_attr')->where('id',$id)->setDec('inventory',$param['count']);
                        }
                        $this->insert_records(3,$param['count'],$id);
                        win('出库成功',Url::build('shop_to_shop'));
                        //
                    }
                    Db::name('shop_spec_attr_auding_status')->insert([
                        'auding_text' => $auding_text,
                        'count' => $param['count'],
                        'bit' => 0,
                        'type' => 3,
                        'spec_id' => $param['id'],
                        'auding_status' => $param['auding_status'],
                        'auding_id' => $manage_id,
                        'role_id' => $role_id,
                        'create_time' => date('Y-m-d H:i:s',time())

                    ]);

                    Db::name('shop_spec_attr')->where('id',$param['id'])->setField('reason',''); //成功 就没有失败原因 清空
                    win('审核完毕',Url::build('shop_to_shop'));
                }


            }

        }

        $shop_list = Db::name('shop')->where('is_delete',1)->where('auding_status',2)->select();
        $shenhe = Db::name('shop_spec_attr_auding_status')
            ->alias('s')
            ->join('manager m','s.auding_id = m.id')
            ->where(['spec_id' => $param['id'],'type' => 3])
            ->find();
        $records = Db::name('shop_spec_attr_auding_status')
            ->alias('s')
            ->join('manager m','s.auding_id = m.id','left')
            ->where(['spec_id' => $param['id'],'type' => 3])
            ->select()->toArray();
        foreach ($records as $k => &$v){
            if($v['role_id'] == 11){
                $v['level'] = '一级审核';
            }
            if($v['role_id'] == 12){
                $v['level'] = '二级审核';
            }
            if($v['role_id'] == 13){
                $v['level'] = '三级审核';
            }


        }

        return view('',['shop_list' => $shop_list,'item' => $shenhe,'records' => $records]);
    }


    public function insert_records($type,$count,$spec_id = 0,$shop_id = 0){
        Db::name('inevntory_records')->insert(['type' => $type,'count' => $count,'spec_id' => $spec_id,'shop_id' => $shop_id,'create_time' => date('Y-m-d H:i:s',time())]);
    }

    public function records()
    {
        $param = Request::instance()->param();
        $where = [];
        if (!empty($param['type'])) $where['ir.type'] = ['eq', $param['type']];
        if (!empty($param['title'])) $where['sg.title|ir.count|ssa.attribute'] = ['like', '%'.$param['title'].'%'];
        if (!empty($param['shop_id'])) $where['s.id'] = ['eq', $param['shop_id']];
        $data = Db::name('inevntory_records ir')
            ->join('shop_spec_attr ssa', 'ir.spec_id = ssa.id', 'left')
            ->join('shop_goods sg','ssa.goods_id = sg.id')
            ->join('shop s', 'ir.shop_id = s.id', 'left')
            ->field('ir.*,s.shop_title,ssa.shop_id shop_id_0_or_1,ssa.goods_id,ssa.attribute,sg.title')
            ->order('ir.id', 'desc')
            ->where($where)
            ->paginate(10, false, ['query' => $param]);
        return view('', ['data' => $data]);
    }
    public function daochu(){
        $where = [];
        $param = Request::instance()->param();
        if (!empty($param['type'])) $where['ir.type'] = ['eq', $param['type']];
        if (!empty($param['title'])) $where['sg.title|ir.count|ssa.attribute'] = ['like', '%'.$param['title'].'%'];
        if (!empty($param['shop_id'])) $where['s.id'] = ['eq', $param['shop_id']];
        $data =Db::name('inevntory_records ir')
            ->join('shop_spec_attr ssa','ir.spec_id = ssa.id','left')
            ->join('shop_goods sg','ssa.goods_id = sg.id')
            ->join('shop s','ir.shop_id = s.id','left')
            ->field('ir.*,s.shop_title,ssa.shop_id shop_id_0_or_1,ssa.goods_id,ssa.attribute,sg.title')
            ->order('ir.id','desc')
            ->where($where)
            ->paginate(10000,false,['query' => $param])->toArray();
        if(!empty($data)){
            foreach ($data['data'] as $k => &$v){
                if($v['type'] == 1) $v['type'] = '总库入库';
                if($v['type'] == 2) $v['type'] = '总库出库门店';
                if($v['type'] == 3) $v['type'] = '门店出库总库';
                if($v['type'] == 4) $v['type'] = '门店出库门店';
            }
        }
        $this->push_coupon($data['data'],'出入库记录导出');

    }
    public function push_coupon($data,$name = 'Excel')
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        error_reporting(E_ALL);
        date_default_timezone_set('Asia/Shanghai');

        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');
        $objPHPExcel = new \PHPExcel();

        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("管理员")
            ->setLastModifiedBy("管理员")
            ->setTitle("电话本导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("备份数据")
            ->setKeywords("excel")
            ->setCategory("result file");
        $objPHPExcel->setActiveSheetIndex(0)
            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
            ->setCellValue('A1', '出入库类型')
            ->setCellValue('B1', '出入库数量')
            ->setCellValue('C1', '出入库规格')
            ->setCellValue('D1', '出入库到门店');
        $sheet1 = ['A', 'B', 'C', 'D', 'I'];

        for ($x = 0; $x < count($sheet1); $x++) {
            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(
                array(
                    'font'      => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' =>
                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
            );
        }

        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/

        $n = 0;
        foreach ($data as $v) {

            $num = $n + 2;
            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
                ->setCellValue('A' . $num, $v['type'])
                ->setCellValue('B' . $num, $v['count'])
                ->setCellValue('C' . $num, $v['goods_id'].'/'.$v['title'].'/'.$v['attribute'])
                ->setCellValue('D' . $num, $v['shop_title']);
            $n++;
        }

        $objPHPExcel->getActiveSheet(0)->setTitle('出入库记录导出');
        $objPHPExcel->setActiveSheetIndex(0);

        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }

    /*
     * 仓库中的商品
     */
    public function warehouse()
    {
        // 获取参数
        $inquire = Request::instance()->param();

        // 搜索条件
        $condition['state'] = ['eq', '2'];
        $condition['member_id'] = ['eq', Session::get('shop_id')];
        if (!empty($inquire['title'])) $condition['title'] = ['like', '%' . $inquire['title'] . '%'];
        if (!empty($inquire['shop_class_id'])) $condition['parenTid'] = ['eq', $inquire['shop_class_id']];

        // 读取店铺分类店铺商品
        $shopClassify = ShopGoodsTypeModel::where(['member_id' => Session::get('shop_id')])->field('id,title,parenTid,parentStr,count')->select();
        // 读取店铺商品
        $data = ShopGoodsModel::where($condition)->field('id,price,parenTid,sort,sale_number,title,create_time,state')->order(['id' => 'desc'])->paginate(10, false, ['query' => $inquire]);

        return $this->fetch('warehouse', [
            'mate_title'   => '仓库中的商品',
            'data'         => $data,
            'classify'     => ClassifyAlias::dimension(Cache::get('goodsType')),
            'shopClassify' => $shopClassify
        ]);
    }

    /*
     * 违规的商品
     */
    public function violation()
    {
        // 获取参数
        $inquire = Request::instance()->param();

        // 搜索条件
        $condition['status'] = ['eq', '3'];
        $condition['member_id'] = ['eq', Session::get('shop_id')];
        if (!empty($inquire['title'])) $condition['title'] = ['like', '%' . $inquire['title'] . '%'];
        if (!empty($inquire['shop_class_id'])) $condition['parenTid'] = ['eq', $inquire['shop_class_id']];

        // 读取店铺分类店铺商品
        $shopClassify = ShopGoodsTypeModel::where(['member_id' => Session::get('shop_id')])->field('id,title,parenTid,parentStr,count')->select();
        // 读取店铺商品
        $data = ShopGoodsModel::where($condition)->field('id,price,parenTid,sort,sale_number,title,create_time,collect,cause')->order(['id' => 'desc'])->paginate(10, false, ['query' => $inquire]);

        return $this->fetch('violation', [
            'mate_title'   => '违规中的商品',
            'data'         => $data,
            'classify'     => ClassifyAlias::dimension(Cache::get('goodsType')),
            'shopClassify' => $shopClassify
        ]);
    }

    /*
     * 店铺分类联动选择
     */
    public function linkage()
    {
        $parenTid = Request::instance()->param('parenTid');
        if (!empty($parenTid))
            return GoodsTypeModel::where(['parenTid' => $parenTid])->field('id,count,title')->order(['id' => 'asc'])->select();
        else
            return false;
    }


    /*
     * 店铺商品添加
     */
    public function create()
    {

        if (Request::instance()->isPost()) {

            $data = Request::instance()->param();

            // 验证
            $validate = Loader::validate('ShopGoods','validate',false,'client');
            if (!$validate->scene('create')->check($data)) fail($validate->getError());

            $model = new ShopGoodsModel();

            // 提交数据
            $dispose = $model->allowField(true)->save($data);

            if (!empty($data['nameAttr'])) {
                // 一对多添加数组
                $flagArr = [];

                for ($i = 0; $i < count($data['nameAttr']); $i++) {
                    $flagArr[$i]['goods_id'] = $model->id;
                    $flagArr[$i]['flag_name'] = $data['nameAttr'][$i];
                    $flagArr[$i]['flag_value'] = $data['valueAttr'][$i];
                }

                $model->flagAttr()->saveAll($flagArr);
            }


            if ($dispose) {
                win('操作成功', Url::build('ShopGoods/index', ['orderId' => 'sort']));
            }

            fail('操作失败');

        }

        //获取分类id
        $goods_id = Request::instance()->param('goods_id');

        if (empty($goods_id)) throw new Exception('goodsId not empty');


        // 读取店铺分类店铺商品
        $shopClassify = ShopGoodsTypeModel::where(['member_id' => Session::get('shop_id')])->field('id,title,parenTid,parentStr,count,sort')->select()->toArray();

        // 读取类别品牌
        $brand = BrandModel::all();

        // 读取店铺规格
        //$attr = ShopGoodsSpecModel::where('goods_type_id' ,['like', '%,' . $goods_id . ',%'])->fetchSql(false)->where('auding_status',2)->where('is_delete',1)->select();
        $attr = ShopGoodsSpecModel::where('goods_type_id' ,'like', '%,' . $goods_id . ',%')->fetchSql(false)->where('auding_status',2)->where('is_delete',1)->select();
//        foreach ($attr as &$value) {
//            // 获取attr参数
//            $value['attribute'] = ShopGoodsAttrModel::where(['spec_id' => $value['id'], 'goods_type_id' => $goods_id,'or'])->select();
//        }

        foreach ($attr as &$value) {
            // 获取attr参数
            ////$value['attribute'] = ShopGoodsAttrModel::where('spec_id','eq',$value['id'])->where('goods_type_id',['eq',$goods_id],['eq',0],'or')->select();
            $value['attribute'] = ShopGoodsAttrModel::where(['spec_id' => $value['id'], 'goods_type_id' => $goods_id])->select();
            //$value['attribute'] = ShopGoodsAttrModel::where('spec_id',['eq',$value['id']], 'goods_type_id',['eq',$goods_id],'or')->select();
        }
        $shop = Db::name('shop')->where('auding_status',2)->where('is_delete',1)->select();

        return $this->fetch('create', [
            "mate_title"   => '店铺商品添加',
            'shopClassify' => ClassifyAlias::dimension($shopClassify),
            'brand'        => $brand,
            'attr'         => $attr,
            'shop' => $shop
        ]);

    }


    /*
     * 库存中的商品编辑
     */
    public function compiler($id)
    {
        if (Request::instance()->isPost()) {

            $data = Request::instance()->param();

            // 验证
            $validate = Loader::validate('ShopGoods');
            if (!$validate->scene('create')->check($data)) fail($validate->getError());

            $model = new ShopGoodsModel();

            // 提交数据
            $dispose = $model->allowField(true)->save($data, ['id' => $id]);

            if (!empty($data['nameAttr'])) {
                // 一对多添加数组
                $flagArr = [];

                for ($i = 0; $i < count($data['nameAttr']); $i++) {

                    if (!empty($data['flag_id'][$i])) {
                        $flagArr[$i]['id'] = $data['flag_id'][$i];
                    }
                    $flagArr[$i]['goods_id'] = $id;
                    $flagArr[$i]['flag_name'] = $data['nameAttr'][$i];
                    $flagArr[$i]['flag_value'] = $data['valueAttr'][$i];
                }

                (new ShopGoodsFlagModel())->saveAll($flagArr);
            }

            if ($dispose) {
                win('操作成功', Url::build('ShopGoods/warehouse', ['orderId' => 'sort']));
            }

            fail('操作失败');

        }

        //获取分类id
        $goods_id = Request::instance()->param('goods_id');

        // 读取数据
        $item = ShopGoodsModel::get($id);

        $item['spec_attr'] = ShopSpecAttr::where(['goods_id' => $id])->select();

        if (empty($goods_id)) $goods_id = $item['goods_id'];;


        // 读取店铺属性
        $attr = ShopGoodsSpecModel::where(['member_id' => Session::get('shop_id'), 'goods_type_id' => ['like', '%,' . $goods_id . ',%']])->where('auding_status',2)->where('is_delete',1)->select();

        foreach ($attr as &$value) {
            // 获取attr参数
            //$value['attribute'] = ShopGoodsAttrModel::where(['spec_id' => $value['id'], 'goods_type_id' => $goods_id])->select();
            $value['attribute'] = ShopGoodsAttrModel::where(['spec_id' => $value['id'], 'goods_type_id' => $goods_id])->select();
        }


        // 读取店铺分类店铺商品
        $shopClassify = ShopGoodsTypeModel::where(['member_id' => Session::get('shop_id')])->field('id,title,parenTid,parentStr,count')->select()->toArray();

        // 读取类别品牌
        $brand = BrandModel::all();

        // 读取商品规格
        $flag_list = ShopGoodsFlagModel::all(['goods_id' => $id]);

        return $this->fetch('create', [
            "mate_title"   => '店铺商品编辑',
            'shopClassify' => ClassifyAlias::dimension($shopClassify),
            'brand'        => $brand,
            'attr'         => $attr,
            'item'         => $item,
            'flag_list'    => $flag_list

        ]);
    }




    /*
     * 店铺商品删除
     */
    public function destroy()
    {

        $id = Request::instance()->param('id');
        $find = Db::name('shop_spec_attr')->where(['goods_id' => $id,'shop_id' =>0])->find();
        if($find){
           // Db::name('shop_spec_attr')->where(['goods_id' => $id,'shop_id' =>0])->delete();
        }
        // 如果有购买中的商品
        $buy = Db::view('member_order_attached', 'goods_id,shop_order_number')
            ->view('member_order', 'shop_order_number,status', 'member_order.shop_order_number = member_order_attached.shop_order_number')
            ->where(['goods_id' => $id, 'status' => ['in', '1,2,6']])
            ->find();

        if (!empty($buy)) fail('该商品还有未收货或未退款的,请先处理');

        // 启动事务
        Db::startTrans();
        try {

            // 删除商品
            Db::name('shop_goods')->where(['id' => $id])->delete();

            // 删除收藏中的该商品
            Db::name('member_collect')->where(['type_id' => '1', 'collect_id' => $id])->delete();

            // 删除浏览记录
            Db::name('member_browse')->where(['goods_id' => $id])->delete();

            // 删除限时抢购表
            Db::name('limited')->where(['goods_id' => $id])->delete();

            // 删除商品套餐表
            $find = Db::view('shop_goods_combo_selected', 'combo_id,goods_id')
                ->view('shop_goods_combo', 'id', 'shop_goods_combo.id = shop_goods_combo_selected.combo_id')
                ->where(['goods_id' => $id])
                ->find();

            if (!empty($find)) {
                Db::view('shop_goods_combo_selected', 'combo_id,goods_id')
                    ->view('shop_goods_combo', 'id', 'shop_goods_combo.id = shop_goods_combo_selected.combo_id')
                    ->where(['goods_id' => $id])
                    ->delete();
            }

            // 删除商品评价表
            Db::name('shop_goods_evaluate')->where(['goods_id' => $id])->delete();

            // 删除属性关联表
            Db::name('shop_spec_attr')->where(['goods_id' => $id])->delete();

            // 删除促销活动表
            Db::name('promotion')->where(['goods_id' => ['in', $id]])->delete();

            // 提交事务
            Db::commit();

            win('操作成功', Url::build('ShopGoods/index', ['orderId' => 'sort']));

        } catch (\Exception $e) {

            // 回滚事务
            Db::rollback();

            win('操作成功', Url::build('ShopGoods/index', ['orderId' => 'sort']));
        }

        // if (ShopGoodsModel::destroy($id)) {
        //     win('操作成功', Url::build('ShopGoods/index', ['orderId' => 'sort']));
        // }
        //
        // fail('操作失败');

    }

    /*
     * 店铺商品编辑
     */
    public function update($id)
    {

        if (Request::instance()->isPost()) {

            $data = Request::instance()->param();
            if(!Request::instance()->param('sp_val/a')){
               //fail('请添加商品规格');
            }
            // 验证
            $validate = Loader::validate('ShopGoods','validate',false,'client');
            if (!$validate->scene('create')->check($data)) fail($validate->getError());

            $model = new ShopGoodsModel();

            // 提交数据
            $dispose = $model->allowField(true)->save($data, ['id' => $id]);

            if (!empty($data['nameAttr'])) {
                // 一对多添加数组
                $flagArr = [];

                for ($i = 0; $i < count($data['nameAttr']); $i++) {

                    if (!empty($data['flag_id'][$i])) {
                        $flagArr[$i]['id'] = $data['flag_id'][$i];
                    }
                    $flagArr[$i]['goods_id'] = $id;
                    $flagArr[$i]['flag_name'] = $data['nameAttr'][$i];
                    $flagArr[$i]['flag_value'] = $data['valueAttr'][$i];
                }

                (new ShopGoodsFlagModel())->saveAll($flagArr);
            }

            if ($dispose !== false) {
                win('操作成功', Url::build('ShopGoods/index', ['orderId' => 'sort']));
            }

            fail('操作失败');

        }

        //获取分类id
        $goods_id = Request::instance()->param('goods_id');

        // 读取数据
        $item = ShopGoodsModel::get($id);

        $item['spec_attr'] = ShopSpecAttr::where(['goods_id' => $id])->where('shop_id',0)->where('attribute','neq','无')->select();

        if (empty($goods_id)) $goods_id = $item['goods_id'];

        // 读取店铺属性
        //$attr = ShopGoodsSpecModel::where('goods_type_id' ,['like', '%,' . $goods_id . ',%'],['eq',''],'or')->fetchSql(false)->where('auding_status',2)->where('is_delete',1)->select();
        $attr = ShopGoodsSpecModel::where('goods_type_id' ,'like', '%,' . $goods_id . ',%')->fetchSql(false)->where('auding_status',2)->where('is_delete',1)->select();
        foreach ($attr as &$value) {
            // 获取attr参数
          $value['attribute'] = ShopGoodsAttrModel::where('spec_id','eq',$value['id'])->where('goods_type_id',['eq',$goods_id],['eq',0],'or')->select();
            //$value['attribute'] = ShopGoodsAttrModel::where('spec_id',['eq',$value['id']], 'goods_type_id',['eq',''])->select();
        }

        //halt($attr->toArray());
        // 读取店铺分类店铺商品
        $shopClassify = ShopGoodsTypeModel::where(['member_id' => Session::get('shop_id')])->field('id,title,parenTid,parentStr,count,sort')->select()->toArray();


        // 读取商品规格
        $flag_list = ShopGoodsFlagModel::all(['goods_id' => $id]);

//        $attr[1] = [
//            ['id' => 1,'goods_type_id' => ',2901,','member_id' => 0,'title' => '门店1','attribute' => [
//                'id' => '2240','goods_type_id' => 2901,'spec_id' => 1, 'title' => '原形'
//                ]
//            ]
//        ];
        //halt($attr->toArray());
        $shop = Db::name('shop')->where('auding_status',2)->where('is_delete',1)->select();
        $r = '';
        $d_shop = Db::name('shop_spec_attr')->field('DISTINCT shop_id')->where('goods_id',$id)->select()->toArray();
        $instr = [];
        if($d_shop){
            foreach ($d_shop as $k => $v){
                $instr[] = $v['shop_id'];
            }
            $r = implode(",",$instr);

        }
        $inventory_sum = Db::name('shop_spec_attr')->where('goods_id',$id)->sum('inventory');
        return $this->fetch('create', [
            "mate_title"   => '店铺商品编辑',
            'shopClassify' => ClassifyAlias::dimension($shopClassify),
            'attr'         => $attr,
            'd_shop' => $r,
            'item'         => $item,
            'shop' => $shop,
            'inventory_sum' => $inventory_sum,
            'flag_list'    => $flag_list

        ]);
    }

    public function inv(){
        $param = Request::instance()->param('shop_id');
        $goods_id = Request::instance()->param('goods_id');
        $data = Db::name('shop_spec_attr')->where('shop_id','in',$param)->where('goods_id',$goods_id)->column('inventory');
        return json_encode($data);
    }
    public function invv(){
        $param = Request::instance()->param('shop_id');
        $goods_id = Request::instance()->param('goods_id');
        $data = Db::name('shop_spec_attr')->where('shop_id','in',$param)->where('goods_id',$goods_id)->column('');
        return json_encode($data);
    }

    public function kc(){
        $shop_id = Request::instance()->param('shop_id');
        $attr = Request::instance()->param('attr');
        $goods_id = Request::instance()->param('goods_id');
        $data = Db::name('shop_spec_attr')->where('shop_id','in',$shop_id)->where('goods_id',$goods_id)->where('attribute',$attr)->value('inventory');
        return json_encode($data);
    }

    /*
     * 猜你喜欢状态改变
     */
    public function related()
    {
        $id = Request::instance()->param('id');
        $related = ShopGoodsModel::where('id', $id)->value('related') == '1' ? 2 : 1;
        if (ShopGoodsModel::where('id', $id)->update(['related' => $related])) {
            return $related;
        }
        return false;
    }

    /*
     * 店铺促销状态
     */
    public function auditing()
    {
        $id = Request::instance()->param('id');
        $recommend = ShopGoodsModel::where('id', $id)->value('recommend') == '1' ? 2 : 1;
        if (ShopGoodsModel::where('id', $id)->update(['recommend' => $recommend])) {
            return $recommend;
        }
        return false;
    }

    /*
     * 促销状态改变
     */
    public function shop_recommend()
    {
        $id = Request::instance()->param('id');
        $promotion = ShopGoodsModel::where('id', $id)->value('state') == '1' ? 2 : 1;
        if (ShopGoodsModel::where('id', $id)->update(['state' => $promotion])) {
            return $promotion;
        }
        return false;
    }

    /*
     * 上架状态改变
     */
    public function dispose_state()
    {
        $id = Request::instance()->param('id');
        $state = ShopGoodsModel::where('id', $id)->value('state') == '1' ? 2 : 1;
        if (ShopGoodsModel::where('id', $id)->update(['state' => $state])) {
            return $state;
        }
        return false;
    }

    /*
     * 上架状态改变
     */
    public function putAway()
    {
        $id = Request::instance()->param('id');
        $state = ShopGoodsModel::where('id', $id)->value('state') == '1' ? 2 : 1;
        if (ShopGoodsModel::where('id', $id)->update(['state' => $state])) {
            return $state;
        }
        return false;
    }

    /*
     * 排列顺序
     */
    public function sorting()
    {

        $id = Request::instance()->param('orderId/a');
        $sort = Request::instance()->param('sort/a');

       if($id){
           foreach ($id as $key => $value) {
               ShopGoodsModel::where('id', $value)->update(['sort' => $sort[$key]]);
           }
       }

        win('操作成功', Url::build('ShopGoods/index', ['orderId' => 'sort']));
    }

    /*
     * 上传组图
     */

}
